<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 左侧文字区域 -->
      <div class="login-left">
        <div class="left-content">
          <h1>心理健康测评系统</h1>
          <p class="slogan">让每个孩子都能享有健康快乐的心灵</p>
          <div class="features">
            <div class="feature-item">
              <el-icon><DocumentChecked /></el-icon>
              <span>专业的心理测评</span>
            </div>
            <div class="feature-item">
              <el-icon><ChatDotRound /></el-icon>
              <span>一对一心理咨询</span>
            </div>
            <div class="feature-item">
              <el-icon><Reading /></el-icon>
              <span>丰富的教育资源</span>
            </div>
            <div class="feature-item">
              <el-icon><UserFilled /></el-icon>
              <span>温暖的社区互动</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧表单 -->
      <div class="login-form">
        <h2>{{ isLogin ? '欢迎回来' : '创建账号' }}</h2>
        <p class="subtitle">{{ isLogin ? '登录您的账号' : '填写信息完成注册' }}</p>
        
        <el-form 
          :model="form" 
          :rules="rules" 
          ref="formRef" 
          class="form"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="form.username" 
              placeholder="用户名"
              prefix-icon="User"
            />
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="form.password" 
              type="password" 
              placeholder="密码"
              prefix-icon="Lock"
              show-password
            />
          </el-form-item>

          <!-- 注册时显示的额外字段 -->
          <template v-if="!isLogin">
            <el-form-item prop="confirmPassword">
              <el-input 
                v-model="form.confirmPassword" 
                type="password" 
                placeholder="确认密码"
                prefix-icon="Lock"
                show-password
              />
            </el-form-item>
            <el-form-item prop="role">
              <el-select 
                v-model="form.role" 
                placeholder="请选择用户类型"
                style="width: 100%"
              >
                <el-option label="留守儿童" value="CHILD" />
                <el-option label="家长" value="PARENT" />
                <el-option label="志愿者/专家" value="EXPERT" />
              </el-select>
            </el-form-item>
          </template>
          
          <!-- 登录时显示的记住密码 -->
          <div v-if="isLogin" class="remember-forgot">
            <el-checkbox v-model="form.remember">记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
          
          <el-button 
            type="primary" 
            class="submit-btn" 
            @click="handleSubmit"
            :loading="loading"
          >
            {{ isLogin ? '登录' : '注册' }}
          </el-button>
          
          <div class="switch-type">
            {{ isLogin ? '还没有账号？' : '已有账号？' }}
            <el-link 
              type="primary" 
              :underline="false"
              @click="switchType"
            >
              {{ isLogin ? '立即注册' : '去登录' }}
            </el-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  User, 
  Lock,
  DocumentChecked,
  ChatDotRound,
  Reading,
  UserFilled
} from '@element-plus/icons-vue'
import request from '../utils/request'
import Cookies from 'js-cookie'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)
const isLogin = ref(true)

const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  role: '',
  remember: false
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  role: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        if (isLogin.value) {
          const loginData = {
            username: form.username,
            password: form.password
          }
          
          const res = await request.post('/auth/login', loginData)
          console.log('Login response:', res)
          
          // 从 res.data 中获取 token 和 userInfo
          if (res.data && res.data.token) {
            // 将 token 和 userInfo 存储到 cookie 中
            const expires = form.remember ? 7 : 1 // 记住我则保存7天，否则保存1天
            Cookies.set('token', res.data.token, { expires })
            Cookies.set('userInfo', JSON.stringify(res.data.userInfo), { expires })
            
            ElMessage.success('登录成功')
            
            // 如果有重定向地址，跳转到重定向地址
            const redirect = route.query.redirect || '/'
            router.push(redirect)
          } else {
            ElMessage.error('登录失败：返回数据格式错误')
          }
        } else {
          await request.post('/auth/register', {
            username: form.username,
            password: form.password,
            role: form.role
          })
          ElMessage.success('注册成功')
          isLogin.value = true
        }
      } catch (error) {
        console.error('Login error details:', {
          error,
          response: error.response,
          data: error.response?.data
        })
        ElMessage.error(error.response?.data?.message || (isLogin.value ? '登录失败' : '注册失败'))
      } finally {
        loading.value = false
      }
    }
  })
}

const switchType = () => {
  isLogin.value = !isLogin.value
  formRef.value?.resetFields()
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.login-box {
  width: 900px;
  height: 500px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  overflow: hidden;
}

.login-left {
  flex: 1;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.left-content {
  max-width: 320px;
}

.left-content h1 {
  font-size: 28px;
  margin-bottom: 20px;
  font-weight: 500;
}

.slogan {
  font-size: 16px;
  opacity: 0.9;
  margin-bottom: 40px;
  line-height: 1.6;
}

.features {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.feature-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.feature-item .el-icon {
  font-size: 24px;
}

.feature-item span {
  font-size: 16px;
}

.login-form {
  flex: 1;
  padding: 40px;
  display: flex;
  flex-direction: column;
}

h2 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 10px;
}

.subtitle {
  color: #909399;
  margin-bottom: 30px;
}

.form {
  width: 100%;
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.submit-btn {
  width: 100%;
  padding: 12px 0;
  margin-bottom: 20px;
}

.switch-type {
  text-align: center;
  color: #606266;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .login-box {
    width: 90%;
    height: auto;
    flex-direction: column;
  }

  .login-left {
    padding: 30px 20px;
    text-align: center;
  }

  .left-content {
    max-width: 100%;
  }

  .features {
    display: none; /* 在移动端隐藏特性列表 */
  }

  .login-form {
    padding: 30px 20px;
  }
}
</style> 